package util;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 框架提供Http客户端组件
 * Created by gulixing@msn.com on 2018/12/18.
 */
public class HttpClienter {

    private  static int SOCKET_TIMEOUT = 10*1000;
    private  static int READ_TIMEOUT_SEC = 60;
    private  static int CONNECTION_TIMEOUT = 2*1000;

    /**
     * 提供基于HttpComponents实现的RestTemplate
     * 默认实现有连接池、超时等配置
     * @return */
    public RestTemplate getRestTemplate() {
        return getRestTemplate(READ_TIMEOUT_SEC);
    }

    public RestTemplate getRestTemplate(int READ_TIMEOUT_SEC){
        // 使用HttpComponent构造restTemplate客户端
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient());
        // 设置超时时间
        factory.setReadTimeout(1000 * READ_TIMEOUT_SEC);
        factory.setConnectionRequestTimeout(CONNECTION_TIMEOUT);
        return new RestTemplate(factory);
    }

    @Bean
    private HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(200);
        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(50);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(SOCKET_TIMEOUT) //服务器返回数据(response)的时间，超过该时间抛出read timeout
                .setConnectTimeout(CONNECTION_TIMEOUT)//连接上服务器(握手成功)的时间，超出该时间抛出connect timeout
                .setConnectionRequestTimeout(5000)//从连接池中获取连接的超时时间，超过该时间未拿到可用连接，会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
